package org.particlethink.mapper.impl;

import org.particlethink.config.RequestConfig;
import org.particlethink.context.Context;
import org.particlethink.mapper.ProjectMapper;
import org.particlethink.model.Project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Repository
//@ConditionalOnMissingBean(value = DevProjectMapperImpl.class)
public class ProProjectMapperImpl implements ProjectMapper {

    @Autowired
    private RequestConfig requestConfig;

    @Override
    public List<Project> selectByIds(String token, List<Integer> ids) {
        return this.list(token, null, null, ids);
    }

    @Override
    public Project selectById(String token, Integer id) {
        return this.list(token, null, null).stream().filter(p -> Objects.equals(p.getId(), id)).findFirst().orElse(null);
    }

    @Override
    public List<Project> list(String token, String projectName, String manageLvName) {
        try {
            return ProjectRequestHelper.queryProjects(requestConfig.getUrl(), projectName, manageLvName, token).stream().map(data -> {
                Project project = new Project();
                project.setId(data.getId());
                project.setName(data.getName());
                project.setAddress(data.getAddress());
                project.setManagementLevel(data.getManagementLevel());
                project.setProvince(data.getProvince());
                project.setCity(data.getCity());
                return project;
            }).collect(Collectors.toList());
        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Project> list(String token, String projectName, String manageLvName, List<Integer> intersection) {
        return this.list(token, projectName, manageLvName).stream().filter(d -> {
            if (intersection == null || intersection.isEmpty()) {
                return true;
            }
            return intersection.contains(d.getId());
        }).collect(Collectors.toList());
    }
}
